#include "Acceptor.h"


/*
    note: 需要确认好每个类的成员变量的生命周期，防止内存泄漏
        1.在构造函数时初始化各个成员变量
        2.在析构函数中释放成员变量
        3.确认每个成员变量归哪个类管，比如acceptSock_中的fd归acceptSock_管，所以close(sockfd_)在acceptSock_的析构函数进行
            而acceptChannel_归Acceptor管，所以acceptChannel_的remove在Acceptor的析构函数进行
*/      
Acceptor::Acceptor(EventLoop *loop, sockaddr_in addr, bool reuseport)
    : loop_(loop),
      acceptSock_(sockets::createNonblockingOrDie(addr.sin_family)),
      acceptorChannel_(new Channel(loop_, acceptSock_.fd())),
      listening_(false)
{
    acceptSock_.setReuseAddr(true);
    acceptSock_.setReusePort(reuseport);
    acceptSock_.bindAddr(addr);
    acceptorChannel_->setReadCallback(std::bind(&Acceptor::handleRead, this));
}

Acceptor::~Acceptor()
{
    acceptorChannel_->disableAll();
    acceptorChannel_->remove();
}

void Acceptor::listen()
{
    loop_->assertInLoopThread();
    listening_ = true;
    acceptorChannel_->enableRead();
    acceptSock_.listen();
}

void Acceptor::handleRead()
{
    loop_->assertInLoopThread();
    sockaddr_in addr;
    int connfd = acceptSock_.accept(&addr);
    if (connfd > 0)
    {
        if (newConnectionCallbak_)
        {
            newConnectionCallbak_(connfd, addr);
        }
        else
        {
            sockets::close(connfd);
        }
    }
    else
    {
        std::cout << "in Acceptor::handleRead failed!" << std::endl;
    }
}